const logger = require('../logger');
const db = require('../../db');

class DataSource {
    /*
    constructor() {

    }
    */

    /**
     * 数据源列表
     */
    getDataSourceList(req) {
        let data_source_id = '';
        let condition = {};
        if (req.params) {
            data_source_id = req.params.data_source_id;
            if (data_source_id) {
                condition = { data_source_id };
            }
        }
        logger.data.info('model.dataSource.getDataSourceList req：', req.params);
        return new Promise(function (resolve, reject) {
            // let condition = {};
            db.data_source.findAndCountAll({
                // attributes: [],
                where: condition,
                order: [
                    ['update_time', 'desc']
                ],
            }).then(function (result) {
                resolve(result);
            }, function (err) {
                logger.error.error('model.dataSource.getDataSourceList error：', err);
                reject(err);
            });
        });
    }

    /**
     * 保存数据源
     */
    saveDataSource(req) {
        let reqData = req.body;
        let { data_source_id } = reqData;
        const now = new Date();
        const uid = req.userInfo.uid;
        logger.data.info('model.dataSource.saveDataSource req：', reqData);
        return new Promise(function (resolve, reject) {
            reqData.updator = uid;
            reqData.update_time = now;
            if (Number(data_source_id)) {
                logger.data.info('model.dataSource.saveDataSource update：', reqData);
                db.data_source.update(reqData, {
                    where: { data_source_id }
                }).then(result => {
                    resolve(result[0]);
                }).catch(e => {
                    logger.error.error('model.dataSource.saveDataSource update error：', e);
                    resolve('');
                });
            } else {
                reqData.creator = uid;
                reqData.creat_time = now;
                reqData.status = 1;
                logger.data.info('model.dataSource.saveDataSource create：', reqData);
                db.data_source.create(reqData).then(result => {
                    resolve(result);
                }).catch(e => {
                    logger.error.error('model.dataSource.saveDataSource create error：', e);
                    resolve('');
                });
            }
        });
    }
}


module.exports = new DataSource();
